import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
import 'package:ost_flutter_module/class/entity/store/store_course_detail_entity.dart';
import 'package:ost_flutter_module/network/base_request_model.dart';
import 'package:ost_flutter_module/network/completable_action.dart';
import 'package:ost_flutter_module/network/http_manager.dart';
import 'package:ost_flutter_module/network/url_constants.dart';
import 'package:ost_flutter_module/widget/loading/loading_view.dart';
import 'package:uuid/uuid.dart';

import '../../../../main.dart';

part 'course_detail_page_event.dart';
part 'course_detail_page_state.dart';

class CourseDetailPageBloc
    extends Bloc<CourseDetailPageEvent, CourseDetailPageState> {
  CourseDetailPageBloc() : super(CourseDetailPageInitial());

  BaseRequestModel<StoreCourseDetailEntity> _dataModel =
      BaseRequestModel<StoreCourseDetailEntity>();
  BaseRequestModel<StoreCourseDetailEntity> get dataModel => _dataModel;
  @override
  Stream<CourseDetailPageState> mapEventToState(
    CourseDetailPageEvent event,
  ) async* {
    if (event is CourseDetailPageFetchEvent) {
      yield* _mapFetch(event, action: event.action);
    }
  }

  Stream<CourseDetailPageSuccess> _mapFetch(
    CourseDetailPageFetchEvent event, {
    CompletableAction action,
  }) async* {
    var result =
        await HttpManager.getInstance().syncRequest<StoreCourseDetailEntity>(
      '$store_course_detail/${event.id}',
      baseUrl: BASE_URL_MALL,
      method: Method.GET,
      params: null,
    );

    action?.completer?.complete(true);

    logger.i(result);

    if (result.isSuccess) {
      var data = result.getOrNull;
      _dataModel = _dataModel.copyWith(
        loadingStatus:
            data != null ? LoadingStatus.success : LoadingStatus.empty,
        entity: data,
      );
    } else {
      _dataModel = _dataModel.copyWith(
        loadingStatus: LoadingStatus.error,
        errorMsg: result.exceptionOrNull?.showMsg,
      );
    }

    yield CourseDetailPageSuccess(Uuid().v4());
  }
}
